package com.atguigu.gmall.list.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.dao.GoodsDao;
import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.model.list.*;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.BaseTrademark;
import com.atguigu.gmall.model.product.SkuAttrValue;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ListServiceImpl implements ListService {
    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private ProductFeignClient productFeignClient;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void upperGoods(Long skuId) {
        //一部手机全部索引手机
        Goods goods = new Goods();
        //1：根据skuID查询SkuInfo信息
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        goods.setId(skuInfo.getId());
        goods.setDefaultImg(skuInfo.getSkuDefaultImg());
        goods.setTitle(skuInfo.getSkuName());
        goods.setPrice(skuInfo.getPrice().doubleValue());
        goods.setCreateTime(new Date());
        //2:根据tmId 查询品牌相关数据
        BaseTrademark baseTrademark = productFeignClient.getBaseTrademark(skuInfo.getTmId());
        goods.setTmId(baseTrademark.getId());
        goods.setTmName(baseTrademark.getTmName());
        goods.setTmLogoUrl(baseTrademark.getLogoUrl());
        //3:根据category3Id查询分类视图
        BaseCategoryView baseCategoryView = productFeignClient.
                getBaseCategoryView(skuInfo.getCategory3Id());
        goods.setCategory1Id(baseCategoryView.getCategory1Id());
        goods.setCategory1Name(baseCategoryView.getCategory1Name());
        goods.setCategory2Id(baseCategoryView.getCategory2Id());
        goods.setCategory2Name(baseCategoryView.getCategory2Name());
        goods.setCategory3Id(baseCategoryView.getCategory3Id());
        goods.setCategory3Name(baseCategoryView.getCategory3Name());
        //4：根据skuId 查询 sku_attr_value   base_attr_info  base_attr_value
        List<SkuAttrValue> skuAttrValueList = productFeignClient.getSkuAttrValue(skuId);
        //private List<SearchAttr> attrs;//平台属性集合  Stream流 偷天换日
        List<SearchAttr> searchAttrList = skuAttrValueList.stream().map(skuAttrValue -> {
            SearchAttr searchAttr = new SearchAttr();
            searchAttr.setAttrId(skuAttrValue.getBaseAttrInfo().getId());
            searchAttr.setAttrName(skuAttrValue.getBaseAttrInfo().getAttrName());
            searchAttr.setAttrValue(skuAttrValue.getBaseAttrValue().getValueName());
            return searchAttr;
        }).collect(Collectors.toList());
        goods.setAttrs(searchAttrList);
        //保存索引库
        goodsDao.save(goods);
    }

    @Override
    public void lowerGoods(Long skuId) {
//2：SpringDataES  删除方式   Mybatis-Plus 相同的
        goodsDao.deleteById(skuId);
    }

    //增加热度 评分
    @Override
    public void hotScore(Long skuId) {

        //1:通过缓存  进行缓冲    10更新一次ES  五大数据类型
        Double hotScore = redisTemplate.opsForZSet().incrementScore("hotScore", skuId, 1);
        /**
         *  小明  语文 100 英语 80 数学 90
         *  小线  语文 90 英语 70 数学 89
         *   ......
         *   hotScore  1号商品 88 2号商品 99 3号商品 77 。。。。
         *   评论    1号商品 99  2号商品 99 3号商品 77 。。。。
         */
        if (hotScore % 10 == 0) {
            //1:查询ES库 此商品的评分
            Optional<Goods> byId = goodsDao.findById(skuId);
            Goods goods = byId.get();
            //2:将此评分加分
            goods.setHotScore(Math.round(hotScore));//8.0  8
            //3:此商品保存回ES库
            goodsDao.save(goods);
            //ES 添加 修改 删除 速度快吗？ 超慢
            //ES 查询速度超 快
        }
    }

    @Override
    public SearchResponseVo search(SearchParam searchParam) {

        SearchResponseVo vo = null;
        try {
            //1:构建搜索请求对象
            SearchRequest searchRequest = buildSearchRequest(searchParam);
            //2:执行搜索
            SearchResponse searchResponse = restHighLevelClient.
                    search(searchRequest, RequestOptions.DEFAULT);
            //3:解析结果对象
            vo = parseSearchResponse(searchResponse);
            //当前页
            vo.setPageNo(searchParam.getPageNo());
            //每页数
            vo.setPageSize(searchParam.getPageSize());
            //总页数 == （总条数 + 每页数 -1)/每页数
            vo.setTotalPages((vo.getTotal() + vo.getPageSize() - 1) / vo.getPageSize());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return vo;

    }

    //解析结果
    private SearchResponseVo parseSearchResponse(SearchResponse searchResponse) {
        SearchResponseVo vo = new SearchResponseVo();
        //取出hits
        SearchHits hits = searchResponse.getHits();
        //拿一堆聚合并转成map
        Map<String, Aggregation> stringAggregationMap = searchResponse.getAggregations().asMap();

        //拿出aggTmId的聚合 Aggregation是个接口 所以要强转成它的实现类ParsedLongTerms
        ParsedLongTerms aggTmId = (ParsedLongTerms) stringAggregationMap.get("aggTmId");
        //解析品牌集合
        //吧bucket换成SearchResponseTmVo
        List<SearchResponseTmVo> trademarkList =
                aggTmId.getBuckets().stream().map(bucket -> {
                    SearchResponseTmVo tmVo = new SearchResponseTmVo();
                    //取出id并转成long类型
                    tmVo.setTmId(Long.parseLong(((Terms.Bucket) bucket).getKeyAsString()));
                    //品牌名称
                    ParsedStringTerms aggTmName = ((Terms.Bucket) bucket).getAggregations().get("aggTmName");
                    //集合的实际长度为1  就一个数 因为品牌名称是唯一的
                    tmVo.setTmName(aggTmName.getBuckets().get(0).getKeyAsString());
                    //品牌logo
                    ParsedStringTerms aggTmLogoUrl = ((Terms.Bucket) bucket).getAggregations().get("aggTmLogoUrl");
                    tmVo.setTmLogoUrl(aggTmLogoUrl.getBuckets().get(0).getKeyAsString());
                    return tmVo;
                }).collect(Collectors.toList());
        vo.setTrademarkList(trademarkList);


        //解析平台属性
        ParsedNested aggAttr = (ParsedNested)stringAggregationMap.get("aggAttrs");
        ParsedLongTerms aggAttrId = aggAttr.getAggregations().get("aggAttrId");
        List<SearchResponseAttrVo> attrsList = aggAttrId.getBuckets().stream().map(bucket -> {
            SearchResponseAttrVo attrVo = new SearchResponseAttrVo();
            //平台属性ID
            attrVo.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            //平台属性名称
            ParsedStringTerms aggAttrName = ((Terms.Bucket) bucket).getAggregations().get("aggAttrName");
            attrVo.setAttrName(aggAttrName.getBuckets().get(0).getKeyAsString());
            //平台属性值
            ParsedStringTerms aggAttrValue = ((Terms.Bucket) bucket).getAggregations().get("aggAttrValue");
            List<String> attrValueList = aggAttrValue.getBuckets().stream()
                    .map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValueList(attrValueList);
            return attrVo;
        }).collect(Collectors.toList());

        vo.setAttrsList(attrsList);


        //商品结果集
        //取出hits中的hits
        SearchHit[] hits1 = hits.getHits();
        List<Goods> goodsList = Arrays.stream(hits1).map(hit -> {
            Goods goods = JSONObject.parseObject(hit.getSourceAsString(), Goods.class);
            //解释高亮的值
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && highlightFields.size() > 0) {
                HighlightField title = highlightFields.get("title");
                if (title != null) {
                    String hname = title.fragments()[0].toString();
                    goods.setTitle(hname);
                    System.out.println(hname);
                }
            }
            return goods;
        }).collect(Collectors.toList());
        vo.setGoodsList(goodsList);
        //分页  总条数
        vo.setTotal(hits.getTotalHits());
        System.out.println(hits.getTotalHits());
        return vo;
    }

    //构建对象
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //条件对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //当多个条件的时候 组合条件对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键词 类似 手机
        String keyword = searchParam.getKeyword();
        if (!StringUtils.isEmpty(keyword)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title",keyword)
                    .operator(Operator.AND));
        } else {
            //搜索全部数据
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //品牌 过滤条件 品牌ID：品牌名称
        String trademark = searchParam.getTrademark();
        if (!StringUtils.isEmpty(trademark)) {
            String[] t = StringUtils.split(trademark, ":");
            boolQueryBuilder.must(QueryBuilders.termQuery("tmId", t[0]));
        }
        //一二三级分类
        Long category1Id = searchParam.getCategory1Id();
        if (category1Id != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("category1Id", category1Id));
        }
        Long category2Id = searchParam.getCategory2Id();
        if (category2Id != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("category2Id", category2Id));
        }
        Long category3Id = searchParam.getCategory3Id();
        if (category3Id != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("category3Id", category3Id));
        }
        //4. 平台属性ID：平台属性值：平台属性名称
        String[] props = searchParam.getProps();
        if (props != null && props.length > 0) {
            //父类及其兄弟
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //平台属性ID：平台属性值：平台属性名称
            for (String prop : props) {
                String[] p = prop.split(":");
                BoolQueryBuilder subBoolQuery = QueryBuilders.boolQuery();
                subBoolQuery.must(QueryBuilders.
                        termQuery("attrs.attrId", p[0]));
                subBoolQuery.must(QueryBuilders.
                        termQuery("attrs.attrValue", p[1]));
                 //将子类放到attr里面  不对数据进行操作
                boolQuery.must(QueryBuilders.
                        nestedQuery("attrs", subBoolQuery, ScoreMode.None));
            }
            //将封装好的父类boolQuery放到里面返回
            boolQueryBuilder.filter(boolQuery);
        }

        //构建条件对象
        searchSourceBuilder.query(boolQueryBuilder);
        //排序  order   1:asc  1:desc   |   2:asc 2:desc |  ...
        String order = searchParam.getOrder();
        if (!StringUtils.isEmpty(order)) {
            String[] o = order.split(":");
            String field = null;
            switch (o[0]) {
                case "1":
                    field = "hotScore";
                    break;
                case "2":
                    field = "price";
                    break;
            }
            searchSourceBuilder.sort(field, o[1].
                    equalsIgnoreCase(SortOrder.ASC.toString()) ? SortOrder.ASC : SortOrder.DESC);
        }

        //分页
        Integer pageNo = searchParam.getPageNo();
        Integer pageSize = searchParam.getPageSize();
        //开始航 limit开始航，每页数
        searchSourceBuilder.from((pageNo - 1) * pageSize);
        searchSourceBuilder.size(pageSize);

        // 高亮 手机是红色
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder
                .field("title")
                .preTags("<span style='color:red'>")
                .postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //品牌聚合
        searchSourceBuilder.aggregation(
                AggregationBuilders.terms("aggTmId").field("tmId").size(80)
                        .subAggregation(AggregationBuilders.terms("aggTmName").field("tmName").size(80))
                        .subAggregation(AggregationBuilders.terms("aggTmLogoUrl").field("tmLogoUrl").size(80)));

        //平台属性聚合
        searchSourceBuilder.aggregation(
                AggregationBuilders.nested("aggAttrs", "attrs")
                        .subAggregation(AggregationBuilders.terms("aggAttrId").field("attrs.attrId")
                                .subAggregation(AggregationBuilders.terms("aggAttrName").field("attrs.attrName"))
                                .subAggregation(AggregationBuilders.terms("aggAttrValue").field("attrs.attrValue"))));
        //打印DSL语句
        System.out.println(searchSourceBuilder.toString());

        //请求ES
        SearchRequest searchRequest = new SearchRequest();
        //设置要搜索的索引库的名字
        searchRequest.indices("goods");
        //构建索引对象
        searchRequest.source(searchSourceBuilder);

        return searchRequest;
    }
}




















